﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;

namespace Group_Mail
{
    public delegate void SendCompleteEventHandler(string to);

    public delegate void SendFailEventHandler(string message);

    public class Job
    {
        private readonly ManualResetEvent doneEvent;

        public Job(Account from, Group to, Recipient recipient, Message message, ManualResetEvent doneEvent)
        {
            From = from;
            To = to;
            Message = message;
            Recipient = recipient;
            this.doneEvent = doneEvent;
        }

        public Account From { get; set; }
        public Group To { get; set; }
        public Recipient Recipient { get; set; }
        public Message Message { get; set; }

        private static void OnSendComplete(string to)
        {
            if (SendComplete != null)
            {
                SendComplete(to);
            }
        }

        public static event SendCompleteEventHandler SendComplete;
        public static event SendFailEventHandler SendFail;

        private static void OnSendFail(string message)
        {
            if (SendFail != null)
            {
                SendFail(message);
            }
        }

        public void Send(object threadContext)
        {
            try
            {
                var htmlBody = ProcessBody(Message.HtmlBody);
                var email = Recipient.GetFieldValue(To.EmailField);
                var mailMessage = new MailMessage(From.Email, email, Message.Subject,
                                                  htmlBody);
                mailMessage.BodyEncoding = Encoding.UTF8;
                mailMessage.SubjectEncoding = Encoding.UTF8;
                mailMessage.IsBodyHtml = true;

                var smtpClient = new SmtpClient(From.SmtpServer, From.SmtpServerPort);
                smtpClient.Credentials = new NetworkCredential(From.SmtpServerUser, From.SmtpServerPassword, "");
                smtpClient.EnableSsl = From.EnableSsl;
                smtpClient.Send(mailMessage);
                OnSendComplete(email);
            }
            catch (Exception ex)
            {
                OnSendFail(ex.Message);
            }

            doneEvent.Set();
        }

        private string ProcessBody(string str)
        {
            var retval = str;
            foreach (var field in To.Fields)
            {
                var value = Recipient.GetFieldValue(field.Name);
                retval = retval.Replace(string.Format("${0}$", field.Name), value);
            }
            return retval;
        }
    }
}